from __future__ import division
from bsccommonlib.csv_persister import CsvPersister
from target_models import TargetObject, TargetSubmit
import datetime
import utils
from correct_unit import correct_unit

class TargetStatusEvulator(object):
    def __init__(self, csv_file):
        self.target_object_list = CsvPersister(csv_file).get_list(TargetObject)

        for target_item in self.target_object_list:
            target_file_name = utils.get_target_file_name(csv_file, target_item.id)
            target_submit_list = CsvPersister(target_file_name).get_list(TargetSubmit)
            point_sum = 0
            for submit in target_submit_list:
                point_sum = submit.point + point_sum
            target_item.done_work = point_sum

            if target_item.start_date.toordinal() > datetime.date.today().toordinal():
                target_item.status = 'PENDING'
                target_item.days_left = target_item.start_date.toordinal() - datetime.date.today().toordinal()
                target_item.need_work = 'X'
            elif target_item.start_date.toordinal() + target_item.duration < datetime.date.today().toordinal():
                if point_sum >= target_item.target_value:
                    target_item.status = 'SUCCESS'
                else:
                    target_item.status = 'FAILED'
                target_item.days_left = 'EXPIRED'
                target_item.need_work = 'X'

            else:
                elapsed = datetime.date.today().toordinal() - target_item.start_date.toordinal() + 1
                step_value = target_item.target_value / target_item.duration
                if point_sum >= elapsed * step_value:
                    target_item.status = 'GOOD'
                elif point_sum >= (elapsed - 1) * step_value:
                    target_item.status = 'IN PROGRESS'
                else:
                    target_item.status = 'BAD'
                target_item.days_left = target_item.start_date.toordinal() + target_item.duration - datetime.date.today().toordinal()
                target_item.need_work = self._get_need_work(target_item.unit, (elapsed * step_value) - point_sum)

            if target_item.increase == 1:
                target_item.actual_target = target_item.initial_status + target_item.target_value
            else:
                target_item.actual_target = target_item.initial_status - target_item.target_value

    def _get_need_work(self, unit, value):
        (value, unit) = correct_unit(value, unit)
        return '%.2f' % value + " " + unit


    def get_status_list(self):
        return self.target_object_list
